﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PipeLineSimulation.App
{
    public class ApplicationFactory
    {
        public delegate Task ApplicationDelegate(string context);

        public ApplicationFactory()
        {
            Components = new List<Func<ApplicationDelegate, ApplicationDelegate>>();
        }

        public List<Func<ApplicationDelegate, ApplicationDelegate>> Components;

        public void Use(Func<ApplicationDelegate, ApplicationDelegate> func)
        {
            Components.Add(func);
        }

        public ApplicationDelegate Build()
        {
            Components.Reverse();

            Console.WriteLine("Pre 404 Start");
            ApplicationDelegate app = async c =>
            {
                Console.WriteLine("404 Start");
                Console.WriteLine(c);
                Console.WriteLine("404 End");
                await Task.CompletedTask;
            };

            foreach (var component in Components)
            {
                app = component.Invoke(app);
            }

            return app;
        }
    }
}
